<?php

App::uses('Component', 'Controller');
App::uses('AttachUtil', 'Lib');

class UploadComponent extends Component {
	
    var $errors = array(); 
    var $controller; 
    var $model; 
     
    function startup(Controller $controller) { 
      $this->controller = $controller; 
    } 

	protected function save($type, $file) {
		try {
			$fileUploaded = array();
    	    $isMobile = $this->controller->request->is('mobile');
		    $this->controller->loadModel('Attach');
    		$this->controller->Attach->create();
			// pr($this->request->data["attachTipo"]);die;
    		AttachUtil::upload($this->controller->Attach, $file, $type, $this->controller->Session->read("Auth.User.id"));
			// pr($this->controller->Attach->data);
			if ($this->controller->Attach->attachTipo->data["AttachTipo"]["thumb"]) {
			// if ($this->controller->Attach->attachTipo->field("thumb")) {
				try {
					$this->controller->Thumb->generateThumb($this->controller->Attach->getAbsolutePath(), $this->controller->Attach->filename, $this->controller->Attach->field("tipo"),$isMobile);
		    	} catch (Exception $e) {
					$this->controller->Attach->delete();
					throw $e;
		    	}
			}
	        $fileUploaded['id']=$this->controller->Attach->id;
	        $fileUploaded['webpath']=$this->controller->Attach->getWebFile();
	        $fileUploaded['thumb_webpath']=$this->controller->Attach->getThumbFile();
			return $fileUploaded;
        } catch (Exception $e) {
            throw $e;
        }
    }

	public function execute() {
        $filesuploaded = array();
		try {
            foreach ($_FILES as $type => $file) {
            	// verifico che sia un post di file multipli
            	if (is_array($file["name"])) {
            		// invio multiplo
            		$files = $this->reArrayFiles($file);
					foreach ($files as $f) {
						$this->_execute($filesuploaded, $type, $f);
					}
            	} else {
					$this->_execute($filesuploaded, $type, $file);
            	}
            }
            return $filesuploaded;
        } catch (Exception $e) {
	    	CakeLog::error($e->getMessage());
			throw $e;
        }
    }
	
	private function _execute(&$filesuploaded, $type, $file) {
		// verifico che non ci sia errore di file non postato (4)
		if ($file["error"]==4)
			return;
		if($file["error"]>0){
			throw new Exception(__("Errore imprevisto in fase di invio file, codice errore: %s", $file["error"]));
            return;		    
		}
        array_push($filesuploaded,$this->save($type, $file));
	}
	
	private function reArrayFiles(&$file_post) {
	    $file_ary = array();
	    $file_count = count($file_post['name']);
	    $file_keys = array_keys($file_post);
	    for ($i=0; $i<$file_count; $i++) {
	        foreach ($file_keys as $key) {
	            $file_ary[$i][$key] = $file_post[$key][$i];
	        }
	    }
	    return $file_ary;
	}
	


}

?>